package com.mmsj;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

/**
 * @author ChuXuan
 */
public class MainActivity extends AppCompatActivity {

    // 获取按钮组件
    private Button addButton;
    private Button deleteButton;
    private Button updateButton;
    private Button queryButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        // 数据库
        SQLiteDatabase liteDatabase = openOrCreateDatabase("android_database.db", Context.MODE_PRIVATE, null);
        Log.d("MainActivity-Log", "数据库路径：" + liteDatabase.getPath());
        // 创建学生表
        String sql = "CREATE TABLE IF NOT EXISTS student(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)";
        liteDatabase.execSQL(sql);
        Log.d("MainActivity-Log", "创建学生表");

        // 按钮绑定
        // 1.增加学生
        addButton = findViewById(R.id.btn_add);
        addButton.setOnClickListener(v -> {
            // 添加学生
            String addSql = "INSERT INTO student(name, age) VALUES('小明', 18)";
            liteDatabase.execSQL(addSql);
            Log.d("MainActivity-Log", "添加学生");
        });
        // 2.删除学生
        deleteButton = findViewById(R.id.btn_delete);
        deleteButton.setOnClickListener(v -> {
            // 删除学生
            String deleteSql = "DELETE FROM student WHERE id = 1";
            liteDatabase.execSQL(deleteSql);
            Log.d("MainActivity-Log", "删除学生");
        });
        // 3.更新学生
        updateButton = findViewById(R.id.btn_update);
        updateButton.setOnClickListener(v -> {
            // 更新学生
            String updateSql = "UPDATE student SET name = '小红' WHERE id = 1";
            liteDatabase.execSQL(updateSql);
            Log.d("MainActivity-Log", "更新学生");
        });
        // 4.查询全部学生
        queryButton = findViewById(R.id.btn_query);
        queryButton.setOnClickListener(v -> {
            String querySql = "SELECT * FROM student";
            Cursor cursor = liteDatabase.rawQuery(querySql, null);
            int count = cursor.getCount();
            if(count>0){
                while (cursor.moveToNext()){
                    int id = cursor.getInt(0);
                    String name = cursor.getString(1);
                    String age = cursor.getString(2);
                    Log.d("MainActivity-Log", "id:"+id+", name:"+name+", age:"+age);

                }
            }
        });

    }
}